package com.tsd.utils;

import com.tsd.core.cache.CacheOperatorApi;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.utils.ListUtil;
import com.tsd.core.datasource.SpringContextUtil;
import com.tsd.system.dao.SysDataAuthMapper;
import com.tsd.system.entity.SysDataAuthExt;
import com.tsd.system.entity.SysUser;
import com.tsd.system.service.SystemSettingService;
import com.tsd.system.vo.GlobalSetting;

import java.util.List;

/**
 * @ClassName: DataPermissionUtil
 * @Description: TODO
 * @Author: admin
 * @Date: 2022/12/16 12:56
 * @Version: 1.0
 */
public class DataFieldAuthUtil {

    @SuppressWarnings("unchecked")
    public static SysDataAuthExt getSysDataAuthField(String dataAuthCode, SysUser opUser) {
        SystemSettingService systemSettingService = SpringContextUtil.getBean(SystemSettingService.class);
        GlobalSetting setting = null;
        try {
            setting = systemSettingService.getGlobalSetting();
        } catch (Exception ignored) {
        }
        if (setting == null) {
            return null;
        }
        // 判断全局设置是否关闭数据字段授权
        if (GlobalSetting.STATE_DISABLE == setting.getEnable_data_auth_field()) {
            return null;
        }
        String key = opUser.getSid() + "_field";
        CacheOperatorApi<List<SysDataAuthExt>> sysDataAuthCacheOperatorApi = (CacheOperatorApi<List<SysDataAuthExt>>) SpringContextUtil.getBean("sysDataAuthCacheOperatorApi");
        List<SysDataAuthExt> authExtList = sysDataAuthCacheOperatorApi.get(key);
        if (HlpUtils.isEmptyList(authExtList)) {
            SysDataAuthMapper sysDataAuthMapper = SpringContextUtil.getBean(SysDataAuthMapper.class);
            authExtList = sysDataAuthMapper.select4UserDataFieldAuth(opUser.getSid());
            if (!HlpUtils.isEmptyList(authExtList)) {
                sysDataAuthCacheOperatorApi.put(key, authExtList);
            }
        }
        SysDataAuthExt authExt = ListUtil.get(authExtList, t -> t.getCode().equals(dataAuthCode));
        if (authExt == null) {
            authExt = new SysDataAuthExt();
            authExt.setNeed_auth(GlobalSetting.STATE_DISABLE);
        }
        // 判断数据字段授权是否启用
        if (GlobalSetting.STATE_DISABLE == authExt.getNeed_auth()) {
            return null;
        }
        if (HlpUtils.isEmpty(authExt.getAuth_mode())) {
            authExt.setAuth_mode(SysDataAuthExt.AUTH_MODE_CREATOR);
        }
        return authExt;
    }
}
